package com.ErpCoreWeb.Security.Access;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ErpCoreModel.Base.AccessType;
import com.ErpCoreModel.Base.CColumnAccessInRole;
import com.ErpCoreModel.Base.CColumnAccessInUser;
import com.ErpCoreModel.Base.CCompany;
import com.ErpCoreModel.Base.CRole;
import com.ErpCoreModel.Base.CUser;
import com.ErpCoreModel.Framework.CBaseObject;
import com.ErpCoreModel.Framework.CColumn;
import com.ErpCoreModel.Framework.CTable;
import com.ErpCoreModel.Framework.Util;
import com.ErpCoreModel.Report.CReport;
import com.ErpCoreWeb.Common.Global;

/**
 * Servlet implementation class ColumnAccessPanel
 */
@WebServlet("/ColumnAccessPanel")
public class ColumnAccessPanel extends HttpServlet {
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	HttpServletResponse response;

	public CUser m_User = null;
    public CCompany m_Company = null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ColumnAccessPanel() {
        super();
        // TODO Auto-generated constructor stub
    }

    //初始化变量
    void initData()
    {
        if (request.getSession().getAttribute("User") == null)
        {
            try {
				response.sendRedirect("../Login.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return ;
        }
        m_User=(CUser)request.getSession().getAttribute("User");
        if (!m_User.IsRole("管理员"))
        {
        	try {
				response.getWriter().print("没有管理员权限！");
	        	response.getWriter().close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	return ;
        }
        String B_Company_id = request.getParameter("B_Company_id");
		if (Global.IsNullParameter(B_Company_id))
			m_Company = Global.GetCtx(this.getServletContext())
					.getCompanyMgr().FindTopCompany();
		else
			m_Company = (CCompany) Global.GetCtx(this.getServletContext())
					.getCompanyMgr().Find(Util.GetUUID(B_Company_id));
	
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}
	void doProc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		this.request=request;
		this.response=response;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		//初始化变量
	    initData();
	    //
        String Action = request.getParameter("Action");
        if (Action == null) Action = "";

        if (Action.equalsIgnoreCase("GetData"))
        {
            GetData();
            return ;
        }
        else if (Action.equalsIgnoreCase("PostData"))
        {
        	PostData();
            return ;
        }
		
	}

    void GetData()
    {
    	String UType = request.getParameter("UType");
    	if(UType==null)
    		UType="";
        String Uid =  request.getParameter("Uid");
        if(Uid==null)
        	Uid="";
        CUser user = null;
        CRole role = null;
        if (UType.equals( "0")) //用户
        {
            if (!Global.IsNullParameter(Uid))
            {
                user = (CUser)Global.GetCtx(this.getServletContext()).getUserMgr().Find(Util.GetUUID(Uid));
            }
        }
        else if (UType.equals( "1")) //角色
        {
            if (!Global.IsNullParameter(Uid))
            {
                role = (CRole)m_Company.getRoleMgr().Find(Util.GetUUID(Uid));
            }
        }
        String FW_Table_id = request.getParameter("FW_Table_id");
        CTable table = null;
        if (!Global.IsNullParameter(FW_Table_id))
            table = (CTable)Global.GetCtx(this.getServletContext()).getTableMgr().Find(Util.GetUUID(FW_Table_id));

        String sData = "";
        int iCount = 0;
        if (table != null)
        {
            List<CBaseObject> lstObj = table.getColumnMgr().GetList();
            iCount = lstObj.size();

            for (CBaseObject obj : lstObj)
            {
                CColumn column = (CColumn)obj;
                int iRead = 0;
                int iWrite = 0;
                if (UType.equals( "0") && user != null) //用户
                {
                    //管理员有所有权限
                    if (user.IsRole("管理员"))
                    {
                        iRead = 1;
                        iWrite = 1;
                    }
                    else
                    {
                        CColumnAccessInUser caiu = user.getColumnAccessInUserMgr().FindByColumn(column.getId());
                        if (caiu != null)
                        {
                            if (caiu.getAccess() == AccessType.read)
                                iRead = 1;
                            else if (caiu.getAccess() == AccessType.write)
                            {
                                iRead = 1;
                                iWrite = 1;
                            }
                        }
                        else  //没有手动设置字段权限， 则默认都可写
                        {
                            iRead = 1;
                            iWrite = 1;
                        }
                    }
                }
                else if (UType.equals( "1") && role != null) //用户
                {
                    //管理员有所有权限
                    if (role.getName().equalsIgnoreCase("管理员"))
                    {
                        iRead = 1;
                        iWrite = 1;
                    }
                    else
                    {
                        CColumnAccessInRole cair = role.getColumnAccessInRoleMgr().FindByColumn(column.getId());
                        if (cair != null)
                        {
                            if (cair.getAccess() == AccessType.read)
                                iRead = 1;
                            else if (cair.getAccess() == AccessType.write)
                            {
                                iRead = 1;
                                iWrite = 1;
                            }
                        }
                        else  //没有手动设置字段权限， 则默认都可写
                        {
                            iRead = 1;
                            iWrite = 1;
                        }
                    }
                }
                String sRow = String.format("\"id\":\"%s\",\"Name\":\"%s\",\"Read\":\"%d\",\"Write\":\"%d\",", column.getId().toString(), column.getName(), iRead, iWrite);

                sRow = "{" + sRow + "},";
                sData += sRow;
            }
        }
        if(sData.length()>0 && sData.endsWith(","))
        	sData = sData.substring(0, sData.length()-1);
        sData = "[" + sData + "]";
        String sJson = String.format("{\"Rows\":%s,\"Total\":\"%d\"}"
            , sData, iCount);

        try {
			response.getWriter().print(sJson);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

    void PostData()
    {
		try {
			String UType = request.getParameter("UType");
			String Uid = request.getParameter("Uid");
			String FW_Table_id = request.getParameter("FW_Table_id");
			String postData = request.getParameter("postData");
			CUser user = null;
			CRole role = null;
			CTable table = (CTable) Global.GetCtx(this.getServletContext())
					.getTableMgr().Find(Util.GetUUID(FW_Table_id));
			if (UType.equals( "0")) // 用户
			{
				user = (CUser) Global.GetCtx(this.getServletContext())
						.getUserMgr().Find(Util.GetUUID(Uid));
				// 管理员有所有权限，不能修改！
				if (user.IsRole("管理员")) {
					response.getWriter().print("管理员有所有权限，不能修改！");
					return;
				}
				//
				String[] arr1 = postData.split(";");
				for (String sItem1 : arr1) {
					String[] arr2 = sItem1.split(",");
					UUID columnid = Util.GetUUID(arr2[0]);
					CColumnAccessInUser caiu = user.getColumnAccessInUserMgr()
							.FindByColumn(columnid);
					if (caiu == null) {
						caiu = new CColumnAccessInUser();
						caiu.setFW_Column_id(columnid);
						caiu.setB_User_id(user.getId());
						if (arr2[2].equals( "1"))
							caiu.setAccess(AccessType.write);
						else if (arr2[1].equals( "1"))
							caiu.setAccess(AccessType.read);
						else
							caiu.setAccess(AccessType.forbide);

						CUser user0 = (CUser) request.getSession()
								.getAttribute("User");
						caiu.setCreator(user0.getId());
						user.getColumnAccessInUserMgr().AddNew(caiu);
					} else {
						if (arr2[2].equals( "1"))
							caiu.setAccess(AccessType.write);
						else if (arr2[1].equals( "1"))
							caiu.setAccess(AccessType.read);
						else
							caiu.setAccess(AccessType.forbide);

						CUser user0 = (CUser) request.getSession()
								.getAttribute("User");
						caiu.setUpdator(user0.getId());
						user.getColumnAccessInUserMgr().Update(caiu);
					}
				}
				if (!user.getColumnAccessInUserMgr().Save(true)) {
					response.getWriter().print("保存失败！");
				}
			} else if (UType.equals( "1")) // 角色
			{
				role = (CRole) m_Company.getRoleMgr().Find(Util.GetUUID(Uid));
				// 管理员有所有权限，不能修改！
				if (role.getName().equalsIgnoreCase("管理员")) {
					response.getWriter().print("管理员有所有权限，不能修改！");
					return;
				}
				//
				String[] arr1 = postData.split(";");
				for (String sItem1 : arr1) {
					String[] arr2 = sItem1.split(",");
					UUID columnid = Util.GetUUID(arr2[0]);
					CColumnAccessInRole cair = role.getColumnAccessInRoleMgr()
							.FindByColumn(columnid);
					if (cair == null) {
						cair = new CColumnAccessInRole();
						cair.setFW_Column_id(columnid);
						cair.setB_Role_id(role.getId());
						if (arr2[2].equals( "1"))
							cair.setAccess(AccessType.write);
						else if (arr2[1].equals( "1"))
							cair.setAccess(AccessType.read);
						else
							cair.setAccess(AccessType.forbide);

						CUser user0 = (CUser) request.getSession()
								.getAttribute("User");
						cair.setCreator(user0.getId());
						role.getColumnAccessInRoleMgr().AddNew(cair);
					} else {
						if (arr2[2].equals( "1"))
							cair.setAccess(AccessType.write);
						else if (arr2[1].equals( "1"))
							cair.setAccess(AccessType.read);
						else
							cair.setAccess(AccessType.forbide);

						CUser user0 = (CUser) request.getSession()
								.getAttribute("User");
						cair.setUpdator(user0.getId());
						role.getColumnAccessInRoleMgr().Update(cair);
					}
				}
				if (!role.getColumnAccessInRoleMgr().Save(true)) {
					response.getWriter().print("保存失败！");
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}
